/**
 * @modal: 智能策略手动执行
 */
import CommonModal from '@/components/CommonModal';
import StrategyTable from './components/StrategyTable';
import ExecuteSure from './components/ExecuteSure';
import ExecuteRecord from './components/ExecuteRecord';
import HeaderTips from './components/HeaderTips';
import { Button, message, Alert } from "antd";
import { useState, useEffect } from "react";
import IntelligentSplittingStrategy from "../IntelligentSplittingStrategy";

import Api from "./service";

function ManualExecute(props) {
	const { searchForm, handleOk, handleCancel, operationPage, selectKeys, orderList } = props;
	const [isOk, setIsOk] = useState(false);
	const [open, setOpen] = useState(false);
	const [compOpen, setCompOpen] = useState(null);

	//当前是否更改过数据
	const [hasEdit, setHasEdit] = useState(false);

	//策略列表
	const [strategyData, setStrategyData] = useState({ smartStrategyConfigs: [] });

	useEffect(() => {
		setOpen(true);
		getStrategyList();
	}, []);

	//获取策略列表
	const getStrategyList = async () => {
		START_LOADING();
		const { success, data } = await Api.getStrategyList({
			type: 0
		});
		if (success) {
			setStrategyData(data);
		}
		END_LOADING();
	};

	//保存并执行
	const saveAndExecute = () => {
		if (hasEdit) {
			setCompOpen('executeSure');
		} else {
			handleSaveAndExecute();
		}
	}

	//确认保存和执行规则
	const handleSaveAndExecute = async (isSave = false) => {
		START_LOADING();
		if (isSave) {
			const { success } = await Api.updateStrategyList(strategyData);
			if (!success) {
				END_LOADING();
				return;
			}
		}
		const { success } = await Api.executeStrategy({
			queryCondition: JSON.stringify(searchForm)
		})
		END_LOADING();
		if (success) {
			message.success('操作成功!');
			setIsOk(true);
			setOpen(false);
		}
	}

	//保存策略
	const saveStrategy = async () => {
		START_LOADING();
		const { success } = await Api.updateStrategyList(strategyData);
		END_LOADING();
		if (success) {
			//标记更改
			hasEdit && setHasEdit(false);
			message.success('保存成功');
		}
	}

	const onCancel = () => {
		setOpen(false);
	};

	const afterClose = () => {
		if (isOk) {
			handleOk(2);
		} else {
			handleCancel();
		}
	};

	//策略列表
	const StrategyTableProps = {
		type: 0,
		strategyData: strategyData,
		saveData(val) {
			const obj = { ...strategyData };
			obj.smartStrategyConfigs = val;
			setStrategyData(obj);
			//标记更改
			!hasEdit && setHasEdit(true);
		},
        handleOpenModal() { //打开智能拆单弹窗
			setCompOpen('IntelligentSplittingStrategey');
        }
	}

	//执行策略确认
	const ExecuteSureProps = {
		handleOk(type) {
			if (type == 2) {
				//执行旧规则
				handleSaveAndExecute();
				setCompOpen(null);
			} else {
				//先保存再执行新规则
				handleSaveAndExecute(true);
				setCompOpen(null);
			}
		},
		handleCancel() {
			setCompOpen(null);
		}
	}

	//执行记录
	const ExecuteRecordProps = {
		type: 0,
		handleCancel() {
			setCompOpen(null);
		}
	}

    //智能拆分策略
    const IntelligentSplittingStrategyProps = {
        item: { scene: "autoSplitOrder"},
		searchForm,
		operationPage,
		selectKeys,
		orderList,
		handleCancel() {
            setCompOpen(null);
		},
        handleOk(updateType, data) {
		},
    }

	const modalFooter = (
		<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
			<div>
				<Button onClick={() => setCompOpen('executeRecord')} type="link">执行记录</Button>
			</div>
			<div>
				<Button onClick={onCancel}>取消</Button>
				<Button onClick={saveAndExecute} type="primary">手动执行（注意先保存）</Button>
				<Button onClick={saveStrategy} type="primary">保存</Button>
			</div>
		</div>
	);

	return (
		<CommonModal
			title="智能策略手动执行"
			footer={modalFooter}
			afterClose={afterClose}
			open={open}
			width="762px"
			onCancel={onCancel}
		>
			<div style={{ paddingBottom: '12px' }}>
				<HeaderTips type="manualExecute" />
				<h3 style={{ margin: '12px 0'}}>规则设置（拖动顺序可更换执行）</h3>
				<StrategyTable {...StrategyTableProps} />
			</div>
			{compOpen == 'executeSure' && <ExecuteSure {...ExecuteSureProps} />}
			{compOpen == 'executeRecord' && <ExecuteRecord {...ExecuteRecordProps} />}
			{compOpen == 'IntelligentSplittingStrategey' && <IntelligentSplittingStrategy {...IntelligentSplittingStrategyProps} />}
		</CommonModal>
	);
}

export default ManualExecute;
